package com.swt.shoppingmall.home.adapter;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.swt.shoppingmall.R;
import com.swt.shoppingmall.app.GoodsInfoActivity;
import com.swt.shoppingmall.home.bean.GoodsBean;
import com.swt.shoppingmall.home.bean.ResultBeanData;
import com.swt.shoppingmall.utils.Constants;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;
import com.youth.banner.listener.OnLoadImageListener;
import com.zhy.magicviewpager.transformer.ScaleInTransformer;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 首页HomeFragment页面设置数据
 * Created by swt on 2016/12/23.
 */

public class HomeFragmentAdapter extends RecyclerView.Adapter {

    public static final String GOODS_BEAN = "goodsBean";
    private int screenWidth;//屏幕宽度

    /**
     * 计算屏幕的宽度
     */
    private void basicParamInit() {
        DisplayMetrics metric = new DisplayMetrics();
        mActivity.getWindowManager().getDefaultDisplay().getMetrics(metric);
        screenWidth = metric.widthPixels;

    }

    /**
     * 广告条幅类型 Banner
     */
    public static final int BANNER = 0;

    /**
     * 频道类型 GridView
     */
    public static final int CHANNEL = 1;

    /**
     * 活动类型 ViewPage
     */
    public static final int ACTION = 2;

    /**
     * 秒杀类型 ViewPage
     */
    public static final int SECKILL = 3;

    /**
     * 推荐类型 ViewPage
     */
    public static final int RECOMMEND = 4;

    /**
     * 热卖类型 ViewPage
     */
    public static final int HOT = 5;

    /**
     * 当前类型
     */
    private int currentType = 0;

    private Activity mActivity;
    private ResultBeanData.ResultBean resultBean;
    private final LayoutInflater mLayoutInflater;

    public HomeFragmentAdapter(Activity mActivity, ResultBeanData.ResultBean resultBean) {
        this.mActivity = mActivity;
        this.resultBean = resultBean;
        mLayoutInflater = LayoutInflater.from(mActivity);//用于初始化布局文件
        basicParamInit();
    }

    /**
     * 创建ViewHolder 相当于ListView中的getView()方法
     *
     * @param parent
     * @param viewType 当前的类型
     * @return
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        if (BANNER == viewType) {
            return new BannerViewHolder(mActivity, mLayoutInflater.inflate(R.layout.banner_viewpager, null));
        } else if (CHANNEL == viewType) {
            return new ChannelViewHolder(mActivity, mLayoutInflater.inflate(R.layout.channel_gridview, null));
        } else if (ACTION == viewType) {
            return new ActionViewHolder(mActivity, mLayoutInflater.inflate(R.layout.act_item, null));
        } else if (SECKILL == viewType) {
            return new SeckillViewHolder(mActivity, mLayoutInflater.inflate(R.layout.seckill_item, null));
        } else if (RECOMMEND == viewType) {
            return new RecommendViewHolder(mActivity, mLayoutInflater.inflate(R.layout.recommend_item, null));
        } else if (HOT == viewType) {
            return new HotViewHolder(mActivity, mLayoutInflater.inflate(R.layout.hot_item, null));
        }
        return null;
    }

    /**
     * 相当于geiView()中绑定数据模块
     *
     * @param holder
     * @param position
     */
    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        if (BANNER == getItemViewType(position)) {
            BannerViewHolder bannerViewHolder = (BannerViewHolder) holder;
            bannerViewHolder.setData(resultBean.getBanner_info());
        } else if (CHANNEL == getItemViewType(position)) {
            ChannelViewHolder channelViewHolder = (ChannelViewHolder) holder;
            channelViewHolder.setData(resultBean.getChannel_info());
        } else if (ACTION == getItemViewType(position)) {
            ActionViewHolder actionViewHolder = (ActionViewHolder) holder;
            actionViewHolder.setData(resultBean.getAct_info());
        } else if (SECKILL == getItemViewType(position)) {
            SeckillViewHolder seckillViewHolder = (SeckillViewHolder) holder;
            seckillViewHolder.setData(resultBean.getSeckill_info());
        } else if (RECOMMEND == getItemViewType(position)) {
            RecommendViewHolder recommendViewHolder = (RecommendViewHolder) holder;
            recommendViewHolder.setData(resultBean.getRecommend_info());
        } else if (HOT == getItemViewType(position)) {
            HotViewHolder hotViewHolder = (HotViewHolder) holder;
            hotViewHolder.setData(resultBean.getHot_info());
        }
    }

    /**
     * 得到类型
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {
        switch (position) {
            case BANNER:
                currentType = BANNER;
                break;
            case CHANNEL:
                currentType = CHANNEL;
                break;
            case ACTION:
                currentType = ACTION;
                break;
            case SECKILL:
                currentType = SECKILL;
                break;
            case RECOMMEND:
                currentType = RECOMMEND;
                break;
            case HOT:
                currentType = HOT;
                break;

        }
        return currentType;
    }

    /**
     * 总共有多少个item
     *
     * @return
     */
    @Override
    public int getItemCount() {
        //开发过程中从1-->2,避免报错
        return 6;
    }

    private class BannerViewHolder extends RecyclerView.ViewHolder {
        private Activity activity;
        private Banner banner;

        public BannerViewHolder(Activity activity, View view) {
            super(view);
            this.activity = activity;
            this.banner = (Banner) view.findViewById(R.id.banner);
        }

        /**
         * 设置Banner的数据
         *
         * @param banner_info
         */
        public void setData(final List<ResultBeanData.ResultBean.BannerInfoBean> banner_info) {
            //得到图片地址
            List<String> imagesUrl = new ArrayList<>();
            for (int i = 0; i < banner_info.size(); i++) {
                String imgUrl = banner_info.get(i).getImage();
                imagesUrl.add(imgUrl);
            }
            //设置循环指示器
            banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
            banner.setBannerAnimation(Transformer.Accordion);//设置手风琴效果
            banner.setImages(imagesUrl, new OnLoadImageListener() {
                @Override
                public void OnLoadImage(ImageView view, Object url) {
                    //设置图片
                    Glide.with(activity).load(Constants.BASE_URL_IMAGE + url).into(view);
                }
            });
            //设置item的点击事件
            banner.setOnBannerClickListener(new OnBannerClickListener() {
                @Override
                public void OnBannerClick(int position) {
                    ResultBeanData.ResultBean.BannerInfoBean bannerInfoBean = banner_info.get(position);
                    GoodsBean goodsBean = new GoodsBean();
                    goodsBean.setFigure(bannerInfoBean.getImage());
//                    goodsBean.setProduct_id(bannerInfoBean.getProduct_id());
//                    goodsBean.setCover_price(bannerInfoBean.getCover_price());
//                    goodsBean.setName(bannerInfoBean.getName());
                    startGoodsInfoActivity(goodsBean);
                }
            });
        }

    }

    /**
     * 跳转到商品详情页
     * @param goodsBean
     */
    private void startGoodsInfoActivity(GoodsBean goodsBean) {
        Intent intent = new Intent(mActivity, GoodsInfoActivity.class);
        intent.putExtra(GOODS_BEAN,goodsBean);
        mActivity.startActivity(intent);
    }


    private class ChannelViewHolder extends RecyclerView.ViewHolder {
        private Activity mActivity;
        private GridView gv_channel;

        public ChannelViewHolder(Activity activity, View view) {
            super(view);
            this.mActivity = activity;
            gv_channel = (GridView) view.findViewById(R.id.gv_channel);

        }

        public void setData(final List<ResultBeanData.ResultBean.ChannelInfoBean> channel_info) {
            //得到了数据 设置GridView适配器
            ChannelAdapter adapter = new ChannelAdapter(mActivity, channel_info);
            gv_channel.setAdapter(adapter);
            //设置item的点击事件
            gv_channel.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Toast.makeText(mActivity, "GridView" + position, Toast.LENGTH_SHORT).show();
                }
            });
        }
    }

    private class ActionViewHolder extends RecyclerView.ViewHolder {
        private Activity mActivity;
        private final ViewPager act_viewpager;

        public ActionViewHolder(Activity activity, View view) {
            super(view);
            this.mActivity = activity;
            act_viewpager = (ViewPager) view.findViewById(R.id.act_viewpager);
        }

        public void setData(final List<ResultBeanData.ResultBean.ActInfoBean> act_info) {
            act_viewpager.setPageMargin(20);//设置页面之间的距离
            act_viewpager.setOffscreenPageLimit(3);//>=3
            //setPageTransformer 决定动画效果
            act_viewpager.setPageTransformer(true, new ScaleInTransformer());//设置滑动渐变
            //1.有数据了
            //2.设置适配器
            act_viewpager.setAdapter(new PagerAdapter() {
                @Override
                public int getCount() {
                    return act_info == null ? 0 : act_info.size();
                }

                /**
                 *
                 * @param view 页面
                 * @param object instantiateItem()这个方法返回的值
                 * @return
                 */
                @Override
                public boolean isViewFromObject(View view, Object object) {
                    return view == object;
                }

                /**
                 *
                 * @param container ViewPage
                 * @param position 对应页面的位置
                 * @return
                 */
                @Override
                public Object instantiateItem(ViewGroup container, final int position) {
                    ImageView imageView = new ImageView(mActivity);
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                    Glide.with(mActivity).load(Constants.BASE_URL_IMAGE + act_info.get(position).getIcon_url()).into(imageView);
                    //添加到容器中
                    container.addView(imageView);

                    //设置点击事件
                    imageView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Toast.makeText(mActivity, "ViewPager" + position, Toast.LENGTH_SHORT).show();
                        }
                    });
                    return imageView;
                }

                @Override
                public void destroyItem(ViewGroup container, int position, Object object) {
                    container.removeView((View) object);
                }
            });
        }
    }

    //相差多少时间-毫秒
    private long dt = 0;

    private class SeckillViewHolder extends RecyclerView.ViewHolder {
        private Activity mActivity;
        private final TextView tv_time_seckill;
        private final TextView tv_more_seckill;
        private final RecyclerView rv_seckill;
        private SeckillRecyclerViewAdapter adapter;
        private Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                dt = dt - 1000;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
                String time = simpleDateFormat.format(new Date(dt));
                tv_time_seckill.setText(time);

                handler.removeMessages(0);
                handler.sendEmptyMessageDelayed(0, 1000);
                if (dt <= 0) {
                    //把消息移除
                    handler.removeCallbacksAndMessages(null);
                }
            }
        };

        public SeckillViewHolder(Activity activity, View view) {
            super(view);
            this.mActivity = activity;
            tv_time_seckill = (TextView) view.findViewById(R.id.tv_time_seckill);
            tv_more_seckill = (TextView) view.findViewById(R.id.tv_more_seckill);
            rv_seckill = (RecyclerView) view.findViewById(R.id.rv_seckill);
        }

        public void setData(final ResultBeanData.ResultBean.SeckillInfoBean seckill_info) {
            ViewGroup.LayoutParams layoutParams = rv_seckill.getLayoutParams();
            //高度等于＝条目的高度＋ 10dp的间距 ＋ 10dp（为了让条目居中）
            layoutParams.height = screenWidth / 3 + dip2px(40);
            rv_seckill.setLayoutParams(layoutParams);

            //设置布局管理器
            rv_seckill.setLayoutManager(new LinearLayoutManager(mActivity, LinearLayoutManager.HORIZONTAL, false));
            //设置数据
            adapter = new SeckillRecyclerViewAdapter(mActivity, seckill_info);
            rv_seckill.setAdapter(adapter);

            //RecycleView设置点击事件
            adapter.setOnSeckillRecyclerView(new SeckillRecyclerViewAdapter.OnSeckillRecyclerView() {
                @Override
                public void onItemClick(int position) {

//                    Toast.makeText(mActivity, "position" + position, Toast.LENGTH_SHORT).show();
                    ResultBeanData.ResultBean.SeckillInfoBean.ListBean listBean = seckill_info.getList().get(position);
                    //商品信息类
                    GoodsBean goodsBean = new GoodsBean();
                    goodsBean.setFigure(listBean.getFigure());
                    goodsBean.setProduct_id(listBean.getProduct_id());
                    goodsBean.setCover_price(listBean.getCover_price());
                    goodsBean.setName(listBean.getName());
                    startGoodsInfoActivity(goodsBean);
                }
            });

            //秒杀倒计时 - 毫秒
            dt = Long.parseLong(seckill_info.getEnd_time()) - Long.parseLong((seckill_info.getStart_time()));
            handler.sendEmptyMessageDelayed(0, 1000);
        }

        /**
         * 将dp转化为px
         */
        private int dip2px(float dip) {
            float v = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, mActivity.getResources().getDisplayMetrics());
            return (int) (v + 0.5f);
        }
    }

    /**
     * 新品推荐
     */
    private class RecommendViewHolder extends RecyclerView.ViewHolder {
        private final GridView gv_recommend;
        private Activity mActivity;
        private final TextView tv_more_recommend;

        public RecommendViewHolder(Activity activity, View view) {
            super(view);
            this.mActivity = activity;
            tv_more_recommend = (TextView) view.findViewById(R.id.tv_more_recommend);
            gv_recommend = (GridView) view.findViewById(R.id.gv_recommend);

        }

        public void setData(final List<ResultBeanData.ResultBean.RecommendInfoBean> recommend_info) {
            RecommendGridViewAdapter adapter = new RecommendGridViewAdapter(mActivity, recommend_info);
            gv_recommend.setAdapter(adapter);
            setGridViewHeightBasedOnChildren(gv_recommend, 3);
            gv_recommend.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                    Toast.makeText(mActivity, "position" + position, Toast.LENGTH_SHORT).show();
                    ResultBeanData.ResultBean.RecommendInfoBean recommendInfoBean = recommend_info.get(position);
                    //商品信息类
                    GoodsBean goodsBean = new GoodsBean();
                    goodsBean.setFigure(recommendInfoBean.getFigure());
                    goodsBean.setProduct_id(recommendInfoBean.getProduct_id());
                    goodsBean.setCover_price(recommendInfoBean.getCover_price());
                    goodsBean.setName(recommendInfoBean.getName());
                    startGoodsInfoActivity(goodsBean);
                }
            });
        }


    }

    private class HotViewHolder extends RecyclerView.ViewHolder {
        private final GridView gv_hot;
        private Activity mActivity;
        private final TextView tv_more_hot;

        public HotViewHolder(Activity activity, View view) {
            super(view);
            this.mActivity = activity;
            tv_more_hot = (TextView) view.findViewById(R.id.tv_more_hot);
            gv_hot = (GridView) view.findViewById(R.id.gv_hot);

        }

        public void setData(final List<ResultBeanData.ResultBean.HotInfoBean> hot_info) {
            HotGridViewAdapter adapter = new HotGridViewAdapter(mActivity, hot_info);
            gv_hot.setAdapter(adapter);
            setGridViewHeightBasedOnChildren(gv_hot, 2);

            gv_hot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    //                    Toast.makeText(mActivity, "position" + position, Toast.LENGTH_SHORT).show();
                    //热卖商品信息类
                    ResultBeanData.ResultBean.HotInfoBean hotInfoBean = hot_info.get(position);
                    //商品信息类
                    GoodsBean goodsBean = new GoodsBean();
                    goodsBean.setFigure(hotInfoBean.getFigure());
                    goodsBean.setProduct_id(hotInfoBean.getProduct_id());
                    goodsBean.setCover_price(hotInfoBean.getCover_price());
                    goodsBean.setName(hotInfoBean.getName());
                    startGoodsInfoActivity(goodsBean);
                }
            });

        }
    }

    /**
     * 计算GridView的高度
     *
     * @param gridView
     */
    public void setGridViewHeightBasedOnChildren(GridView gridView, int colNumber) {
        //开始计算GridView的高度
        ListAdapter listAdapter = gridView.getAdapter();
        if (null == listAdapter) {
            return;
        }
        // 固定列宽，有多少列
        int col = colNumber;
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i += col) {
            //获取listView的每一个Item
            View listItem = listAdapter.getView(i, null, gridView);
            listItem.measure(0, 0);
            // 获取item的高度和
            totalHeight += listItem.getMeasuredHeight();
        }
        ViewGroup.LayoutParams params = gridView.getLayoutParams();
        params.height = totalHeight;

        //设置参数
        gridView.setLayoutParams(params);
    }
}
